package com.framework.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.framework.dao.ter.TerMerchantIncomingDao;
import com.framework.entity.sys.SysAgent;
import com.framework.entity.ter.TerMerchantIncoming;
import com.framework.page.PageUtils;
import com.framework.page.Query;
import com.framework.service.AgentService;
import com.framework.service.TerMerchantIncomingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service("terMerchantIncomingService")
public class TerMerchantIncomingServiceImpl extends ServiceImpl<TerMerchantIncomingDao, TerMerchantIncoming> implements TerMerchantIncomingService {

    @Autowired
    private AgentService agentService;

    @Override
    public List<TerMerchantIncoming> getMerIncomingByToken(String token) {
        SysAgent agent = agentService.queryAgentByToken(token);

        List<TerMerchantIncoming> terMerchantIncomings = selectList(new EntityWrapper<TerMerchantIncoming>()
                .eq("dept_id", agent.getDeptId())
                .eq("del_flag", 0)
                .orderBy("sort", true)
        );
        terMerchantIncomings.stream().filter(
                e -> e.getJumpUrl().contains("{token}")).forEach(e -> e.setJumpUrl(e.getJumpUrl().replace("{token}", token)));
        return terMerchantIncomings;
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        Long deptId = (Long) params.get("deptId");
        Page<TerMerchantIncoming> page = selectPage(new Query<TerMerchantIncoming>(params).getPage(),
                new EntityWrapper<TerMerchantIncoming>()
                        .eq("dept_id", deptId));


        return new PageUtils(page);
    }

    @Override
    public void save(TerMerchantIncoming incoming) {
        incoming.setCreateTime(new Date());
        baseMapper.insert(incoming);
    }

    @Override
    public void deleteByIds(String[] ids) {
        for (String id : ids) {
            TerMerchantIncoming terMerchantIncoming = selectById(id);
            if (terMerchantIncoming != null) {
                terMerchantIncoming.setDelFlag(1);
                updateById(terMerchantIncoming);
            }
        }
    }
}
